package com.example.blog.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.blog.domain.Writings;
import com.example.blog.service.impl.WritingsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class IdUtils {
    private final WritingsServiceImpl writingsService;
    @Autowired
    IdUtils( WritingsServiceImpl writingsService){
        this.writingsService = writingsService;
    }
    public String createUid(){
        List<Writings> writings = writingsService.list();
        long value = Long.MAX_VALUE;
        long id  = Long.parseLong(writings.get(writings.size() - 1).getWid());
        for(long i = id;i< value ;i++){
            if(writingsService.list(new LambdaQueryWrapper<Writings>().eq(Writings::getWid,String.valueOf(i))).size()==0)
               return String.valueOf(i);
        }
        return null;
    }

    /**
     * @description: sha1
     * @author: lvyq
     * @date: 2022/7/8 15:18
     * @version 1.0
     */

    public static String sha1(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        //把字符串转为字节数组
        byte[] b = data.getBytes();
        //使用指定的字节来更新我们的摘要
        md.update(b);
        //获取密文  （完成摘要计算）
        byte[] b2 = md.digest();
        //获取计算的长度
        int len = b2.length;
        //16进制字符串
        String str = "0123456789abcdef";
        //把字符串转为字符串数组
        char[] ch = str.toCharArray();
        //创建一个40位长度的字节数组
        char[] chs = new char[len*2];
        //循环20次
        for(int i=0,k=0;i<len;i++) {
            //获取摘要计算后的字节数组中的每个字节
            byte b3 = b2[i];
            // >>>:无符号右移
            // &:按位与
            //0xf:0-15的数字
            chs[k++] = ch[b3 >>> 4 & 0xf];
            chs[k++] = ch[b3 & 0xf];
        }
        //字符数组转为字符串
        return new String(chs);
    }
}
